package com.lx.demo.b.utils;

import com.lx.MsagesException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by lanyxp on 2021/3/9 10:00
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class IpUtil {

    public static String getSystemIp() {
        try {
            return isWindowsOS() ? InetAddress.getLocalHost().getHostAddress() : getLinuxLocalIp();
        } catch (Exception var1) {
            log.error(var1.getMessage(), var1);
            throw new MsagesException("获取本机IP失败");
        }
    }

    public static boolean isWindowsOS() {
        String osName = System.getProperty("os.name");
        return osName.toLowerCase().contains("windows");
    }

    private static String getLinuxLocalIp() throws SocketException {
        Enumeration en = NetworkInterface.getNetworkInterfaces();

        while (true) {
            NetworkInterface networkInterface;
            String name;
            do {
                do {
                    if (!en.hasMoreElements()) {
                        throw new MsagesException("未获取到IP地址，请检查环境是否正常");
                    }

                    networkInterface = (NetworkInterface) en.nextElement();
                    name = networkInterface.getName();
                } while (name.contains("docker"));
            } while (name.contains("lo"));

            Enumeration enumIpAddr = networkInterface.getInetAddresses();

            while (enumIpAddr.hasMoreElements()) {
                InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    String address = inetAddress.getHostAddress();
                    if (!address.contains("::") && !address.contains("0:0:") && !address.contains("fe80")) {
                        return address;
                    }
                }
            }
        }
    }
}
